package wechat

import (
	"context"
	redis "nearby/biz/dal/cache"
	"nearby/biz/dal/db/repo"
	"strings"

	"github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/cache"
	"github.com/silenceper/wechat/v2/miniprogram"
	miniConfig "github.com/silenceper/wechat/v2/miniprogram/config"
)

var (
	mini *miniprogram.MiniProgram
)

func InitWeChatCli() {
	// 使用memcache保存access_token，也可选择redis或自定义cache
	wc := wechat.NewWechat()
	redisOpts := &cache.RedisOpts{
		Host:        redis.RedisHost,
		Database:    redis.DatabaseForWx,
		Password:    redis.Pwd,
		MaxActive:   10,
		MaxIdle:     10,
		IdleTimeout: 60, //second
	}
	redisCache := cache.NewRedis(redisOpts)
	cfg := &miniConfig.Config{
		Cache: redisCache,
	}
	configMini(cfg)

	mini = wc.GetMiniProgram(cfg)
}

func configMini(cfg *miniConfig.Config) {
	ctx := context.Background()
	kvRepo := repo.NewBizKVRepo(ctx)
	v := kvRepo.GetVal(ctx, "mini_program_conf")
	vv := strings.Split(v, ",")
	cfg.AppID = vv[0]
	cfg.AppSecret = vv[1]
}
